package cn.xiaopengstack.domain.agent.service.execute.auto;

import cn.bugstack.wrench.design.framework.tree.StrategyHandler;
import cn.xiaopengstack.domain.agent.model.entity.AutoAgentExecuteResultEntity;
import cn.xiaopengstack.domain.agent.model.entity.ExecuteCommandEntity;
import cn.xiaopengstack.domain.agent.service.execute.IExecuteStrategy;
import cn.xiaopengstack.domain.agent.service.execute.auto.factory.DefaultAutoAgentExecuteStrategyFactory;
import com.alibaba.fastjson.JSON;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyEmitter;

import java.io.IOException;

/**
 * @author jiangyangang
 */
@Service("auto")
@Slf4j
public class AutoAgentExecuteStrategy implements IExecuteStrategy {
    @Resource
    private DefaultAutoAgentExecuteStrategyFactory factory;

    @Override
    public void execute(ExecuteCommandEntity executeCommandEntity, ResponseBodyEmitter emitter) throws Exception{
        StrategyHandler<ExecuteCommandEntity, DefaultAutoAgentExecuteStrategyFactory.DynamicContext, String> executeHandler = factory.getAgentStrategyHandler();
        DefaultAutoAgentExecuteStrategyFactory.DynamicContext dynamicContext = new DefaultAutoAgentExecuteStrategyFactory.DynamicContext();
        dynamicContext.setEmitter(emitter);
        dynamicContext.setMaxSteps(executeCommandEntity.getMaxSteps() != null ? executeCommandEntity.getMaxSteps() : 3);
        dynamicContext.setCurrentTask(executeCommandEntity.getMessage());

        String result = executeHandler.apply(executeCommandEntity, dynamicContext);
        log.info("Auto Agent执行结果:{}", result);

        try {
            AutoAgentExecuteResultEntity completeResult = AutoAgentExecuteResultEntity.createCompleteResult(executeCommandEntity.getSessionId());
            String sseData = "data: " + JSON.toJSONString(completeResult) + "\n\n";
            emitter.send(sseData);
        } catch (Exception e) {
            log.error("发送完成标识失败：{}", e.getMessage(), e);
        }
    }
}
